package com.jieshuibao.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;

import com.jieshuibao.common.config.Const;
import com.jieshuibao.common.config.Global;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.Answer;
import com.jieshuibao.model.db.Company;
import com.jieshuibao.model.db.PurchaseOrder;
import com.jieshuibao.model.db.Question;
import com.jieshuibao.model.db.QuestionUserKey;
import com.jieshuibao.model.db.RedEnvelopes;
import com.jieshuibao.model.db.Secretly;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.UserDealRecord;
import com.jieshuibao.model.db.UserDrama;
import com.jieshuibao.model.db.UserWx;
import com.jieshuibao.model.db.UserWxExample;
import com.jieshuibao.model.db.Wishbuy;
import com.jieshuibao.model.db.Wishcode;
import com.jieshuibao.model.db.Withdraw;
import com.jieshuibao.model.db.WxOrder;
import com.jieshuibao.model.db.WxRefund;
import com.jieshuibao.model.db.WxRefundExample;
import com.jieshuibao.model.db.WxRefundExample.Criteria;
import com.jieshuibao.model.domain.Article;
import com.jieshuibao.util.DateUtils;
import com.jieshuibao.util.JsonUtil;
import com.jieshuibao.util.NetworkUtil;
import com.jieshuibao.util.PayTypeUtil;
import com.jieshuibao.util.RewardUtil;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.util.WithdrawUtil;
import com.jieshuibao.util.push.PushType;
import com.jieshuibao.wx.po.WxAppPayReq;
import com.jieshuibao.wx.po.WxAppPayRes;
import com.jieshuibao.wx.po.WxEnterpriseReq;
import com.jieshuibao.wx.po.WxEnterpriseRes;
import com.jieshuibao.wx.po.WxJsPayReq;
import com.jieshuibao.wx.po.WxQueryOrderRes;
import com.jieshuibao.wx.po.WxjsPayRes;
import com.jieshuibao.wx.util.PayCommonUtil;
import com.jieshuibao.wx.util.WeiXinPublicUtil;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.pay.request.WxPayUnifiedOrderRequest;
import me.chanjar.weixin.mp.bean.pay.result.WxPayOrderQueryResult;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import net.sf.json.JSONObject;

@Service
public class WeiXinPayService {
	private static final Logger logger = Logger
			.getLogger(WeiXinPayService.class);

	String timeMillis = String.valueOf(System.currentTimeMillis() / 1000);
	String randomString = PayCommonUtil.getRandomString(32);
	
	public static final String SMSAPPID = "8aaf07086619653001661b1865b301fa";

	@Value("${server.url}")
	private String host;

	@Resource
	private RedisService redisService;
	@Resource
	private WxOrderService wxOrderService;
	@Resource
	private QuestionService questionService;
	@Resource
	private QuestionUserService questionUserService;
	@Resource
	private WithdrawService withdrawService;
	@Resource
	private PurchaseOrderService purchaseOrderService;
	@Resource
	private UserService userService;
	@Resource
	private CoreService coreService;
	@Resource
	private TaskExecutor taskExecutor;// 线程池 
	@Resource
	private RedEnvelopesService redEnvelopesService;
	@Resource
	private CompanyService companyService;
	@Resource
	private SecretlyService secretlyService;
	@Resource
	private AnswerService answerService;
	@Resource
	private SmsSendService smsSendService;
	@Resource(name="wxMpService")
	private WxMpService wxMpService;
	@Resource(name="wxAppService")
	private WxMpService wxAppService;
	@Resource
	private WishbuyService wishbuyService;
	@Resource
	private UserDramaService userDramaService;
	@Resource
	private UserWxService userWxService;
	@Resource
	private AdvisoryService advisoryService;
	@Resource
	private VideoBuyHistoryService videoBuyHistoryService;
	
	@Resource
	private UserDealRecordService userDealRecordService;
	@Resource
	private IntegralService IntegralService;
	@Resource
	private PushService pushService;
	@Resource
	private ArticelService articelService;
	
	@Resource
	private WxRefundService wxRefundService;
	
	private String createSign(Map<String, String> packageParams, String signKey) {
		SortedMap<String, String> sortedMap = new TreeMap<>(packageParams);

		StringBuffer toSign = new StringBuffer();
		for (String key : sortedMap.keySet()) {
			String value = packageParams.get(key);
			if (null != value && !"".equals(value) && !"sign".equals(key)
					&& !"key".equals(key)) {
				toSign.append(key + "=" + value + "&");
			}
		}

		toSign.append("key=" + signKey);

		return DigestUtils.md5Hex(toSign.toString()).toUpperCase();
	}

	public boolean checkAPPCallbackDataSignature(Map<String, String> kvm,
			String signature) {
		return signature.equals(this.createSign(kvm, this.wxAppService
				.getWxMpConfigStorage().getPartnerKey()));
	}
	
	/**
	 * app微信支付
	 * @param wxAppPayReq
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Object appPay(WxAppPayReq wxAppPayReq, HttpServletRequest request) {
		WxAppPayRes wxAppPayRes = new WxAppPayRes();
		Double unitPrice = wxAppPayReq.getUnitPrice();
		//TODO 测试微信支付价格写死
//		unitPrice = 0.01;
		int amount = wxAppPayReq.getAmount() == 0 ? 1 : wxAppPayReq.getAmount();
		String productId = wxAppPayReq.getProductId();
		double realPrice = wxAppPayReq.getRealPrice();
		String productName = wxAppPayReq.getProductName();
		String description = productName;
		String phone = wxAppPayReq.getPhone();
		if(StringUtils.isEmpty(phone)){
			logger.error("手机号为空");
			wxAppPayRes.setCode(PayCommonUtil.FAIL_CODE);
			wxAppPayRes.setDes("手机号不能为空");
			return wxAppPayRes;
		}
		if(StringUtils.isEmpty(productId)){
			logger.error("业务编号为空");
			wxAppPayRes.setCode(PayCommonUtil.FAIL_CODE);
			wxAppPayRes.setDes("业务编号不能为空");
			return wxAppPayRes;
		}
		String sn = wxAppPayReq.getOrderNo();
		String productType = wxAppPayReq.getProductType();
		BigDecimal totalAmount = new BigDecimal(unitPrice * amount);
		try {
			if (StringUtils.isEmpty(sn)) {
				sn = UUIDGenerator.getUUID();// 商户订单号
				WxOrder wxOrder = new WxOrder();
				wxOrder.setAmount(amount);
				wxOrder.setId(sn);
				wxOrder.setProductId(productId);
				wxOrder.setProductName(productName);
				wxOrder.setStatus(PayCommonUtil.PAYPENDING_STATUS);
				wxOrder.setSum(totalAmount.doubleValue());
				wxOrder.setTime(new Date());
				wxOrder.setUnitPrice(wxAppPayReq.getUnitPrice());
				wxOrder.setPhone(phone);
				wxOrder.setProductType(productType);
				wxOrder.setTradeType("APP");
				wxOrderService.addWxOrder(wxOrder); // 生成待支付订单
			}

			SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
			parameterMap.put("appid", PayCommonUtil.APPID);
			parameterMap.put("mch_id", PayCommonUtil.MCH_ID);
			parameterMap.put("nonce_str", randomString);
			parameterMap.put("body", description);
			parameterMap.put("out_trade_no", sn);
			parameterMap.put("fee_type", "CNY");
			BigDecimal total = totalAmount.multiply(new BigDecimal(100));
			java.text.DecimalFormat df = new java.text.DecimalFormat("0");
			parameterMap.put("total_fee", df.format(total));
			parameterMap.put("spbill_create_ip", NetworkUtil.getIpAddress(request).equals("0:0:0:0:0:0:0:1")?"127.0.0.1":NetworkUtil.getIpAddress(request));
			parameterMap.put("notify_url", host + "/api/weixin/payCallback");
			parameterMap.put("trade_type", "APP");
			
			Map<String , String> attach = new HashMap<String, String>();
			attach.put("type", productType);
			attach.put("pId", productId);
			attach.put("uId", phone);
			attach.put("price", Double.toString(realPrice));
 			parameterMap.put("attach", JsonUtil.toJson(attach));
 			logger.info(JsonUtil.toJson(attach).length());
			String sign = PayCommonUtil.createSign("UTF-8", parameterMap);
			parameterMap.put("sign", sign);
			String requestXML = PayCommonUtil.getRequestXml(parameterMap);
			logger.info("微信预支付请求报文：" + requestXML);
			String result = PayCommonUtil.httpsRequest(
					PayCommonUtil.API_PAYSERVER, "POST", requestXML);
			logger.error("微信预支付返回报文" + result);
			Map<String, String> map = null;
			map = PayCommonUtil.doXMLParse(result);
			String return_code = map.get("return_code");
			String result_code = map.get("result_code");

			if (return_code.equalsIgnoreCase(PayCommonUtil.SUCCESS)) {
				if (result_code.equalsIgnoreCase(PayCommonUtil.SUCCESS)) {
					SortedMap<String, Object> finalpackage = new TreeMap<String, Object>();
					String randomStr = randomString;
					String timeStamp = timeMillis;
					finalpackage.put("appid", PayCommonUtil.APPID);
					finalpackage.put("partnerid", PayCommonUtil.MCH_ID);
					finalpackage.put("prepayid", map.get("prepay_id"));
					finalpackage.put("package", "Sign=WXPay");
					finalpackage.put("noncestr", randomStr);
					finalpackage.put("timestamp", timeStamp);
					// finalpackage.put("signType", "MD5");

					String sign2 = PayCommonUtil.createSign("UTF-8",
							finalpackage);
					// finalpackage.put("paySign", sign2);
					wxAppPayRes.setCode(PayCommonUtil.SUCCESS_CODE);
					wxAppPayRes.setDes("预支付成功");
					wxAppPayRes.setAppId(PayCommonUtil.APPID);
					wxAppPayRes.setTimeStamp(timeStamp);
					wxAppPayRes.setNonceStr(randomStr);
					wxAppPayRes.setExtend("Sign=WXPay");
					wxAppPayRes.setSign(sign2);
					wxAppPayRes.setSignType("MD5");
					wxAppPayRes.setOrderNo(sn);
					wxAppPayRes.setPrepayid(map.get("prepay_id"));
					wxAppPayRes.setPartnerid(PayCommonUtil.MCH_ID);
					String res = PayCommonUtil.toJson(wxAppPayRes);
					logger.error("预支付返回APP报文信息:" + res);
					return wxAppPayRes;
				} else {
					logger.error("调用微信支付异常");
					wxAppPayRes.setCode(PayCommonUtil.FAIL_CODE);
					wxAppPayRes.setDes("系统繁忙");
					return wxAppPayRes;
				}

			} else {
				logger.error("调用微信支付异常");
				wxAppPayRes.setCode(PayCommonUtil.FAIL_CODE);
				wxAppPayRes.setDes("系统繁忙");
				return wxAppPayRes;
			}
		} catch (IOException e) {
			logger.error("IOException异常:"+e);
			wxAppPayRes.setCode(PayCommonUtil.FAIL_CODE);
			wxAppPayRes.setDes("系统繁忙");
			return wxAppPayRes;
		} catch (JDOMException e) {
			logger.error("JDOMException:JDOM解析异常"+e);
			wxAppPayRes.setCode(PayCommonUtil.FAIL_CODE);
			wxAppPayRes.setDes("系统繁忙");
			return wxAppPayRes;
		}
	}

	public Object jSSDKPayInfo(WxJsPayReq req,HttpServletRequest request) {
		WxjsPayRes res = new WxjsPayRes();
		String code = req.getCode();
		Double unitPrice = req.getUnitPrice();
		int amount = req.getAmount() == 0 ? 1 : req.getAmount();
		String productId = req.getProductId();
		double realPrice = req.getRealPrice();
		String productName = req.getProductName();
		String description = productName;
		String phone = req.getPhone();
		String sn = req.getOrderNo();
		String productType = req.getProductType();
		BigDecimal totalAmount = new BigDecimal(unitPrice * amount);
		totalAmount = totalAmount.multiply(new BigDecimal(100));
		if(StringUtils.isEmpty(code)){
			logger.error("js微信支付code参数为空");
			res.setCode(BaseRes.ERRORPARAM_CODE);
			res.setDes("js微信支付code参数为空");
			return res;
		}
		if(StringUtils.isEmpty(phone)){
			logger.error("js微信支付phone参数为空");
			res.setCode(BaseRes.ERRORPARAM_CODE);
			res.setDes("js微信支付phone参数为空");
			return res;
		}
		if(StringUtils.isEmpty(productId)){
			logger.error("js微信支付productId参数为空");
			res.setCode(BaseRes.ERRORPARAM_CODE);
			res.setDes("js微信支付productId参数为空");
			return res;
		}
			if (StringUtils.isEmpty(sn)) {
				sn = UUIDGenerator.getUUID();// 商户订单号
				WxOrder wxOrder = new WxOrder();
				wxOrder.setAmount(req.getAmount());
				wxOrder.setId(sn);
				wxOrder.setProductId(req.getProductId());
				wxOrder.setProductName(req.getProductName());
				wxOrder.setStatus(PayCommonUtil.PAYPENDING_STATUS);
				wxOrder.setSum(totalAmount.doubleValue());
				wxOrder.setTime(new Date());
				wxOrder.setUnitPrice(req.getUnitPrice());
				wxOrder.setPhone(req.getPhone());
				wxOrder.setProductType(productType);
				wxOrder.setTradeType("JSAPI");
				wxOrderService.addWxOrder(wxOrder); // 生成待支付订单
			}
		try {
			String openId = coreService.getOpenId(code, WeiXinPublicUtil.SRCMP);
//			String openId = "ojFD0vz83cQkyI0Q9pnLqj62DtVM";
			if(StringUtils.isEmpty(openId)){
				logger.error("获取openID错误");
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes("获取openID错误");
				return res;
			}
			WxPayUnifiedOrderRequest prepayInfo = new WxPayUnifiedOrderRequest();
			prepayInfo.setOpenid(openId);
			prepayInfo.setOutTradeNo(sn);
			prepayInfo.setTotalFee(totalAmount.intValue());
			prepayInfo.setBody(description);
			prepayInfo.setTradeType("JSAPI");
			prepayInfo.setSpbillCreateIp(NetworkUtil.getIpAddress(request));
			prepayInfo.setNotifyURL(host + "/api/weixin/payCallback");
			Map<String , String> attach = new HashMap<String, String>();
			attach.put("type", productType);
			attach.put("pId", productId);
			attach.put("uId", phone);
			attach.put("price", Double.toString(realPrice));
			prepayInfo.setAttach(JsonUtil.toJson(attach));
			logger.info("微信公众号支付请求报文：" + JsonUtil.toJson(prepayInfo));
			Map<String, String> payInfo = this.wxMpService.getPayService()
					.getPayInfo(prepayInfo);
			res.setCode(BaseRes.SUCCESS_CODE);
			res.setData(payInfo);
			logger.info("微信公众号支付预支付订单报文：" + JsonUtil.toJson(payInfo));
			return res;
		} catch (WxErrorException e) {
			logger.error(e.getError().toString());
			res.setCode(Global.FAIL);
			res.setDes("系统繁忙");
			return res;
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("获取IP地址异常");
			res.setCode(Global.FAIL);
			res.setDes("系统繁忙");
			return res;
		}
	}
	
	/**
	 * APP支付成功回调
	 * @param map
	 */
	public void afterPaySuc(Map<String , String> map){
		String transaction_id = map.get("transaction_id"); //微信订单号
		String transaction_id_own =  map.get("out_trade_no"); //商户订单号
//		String sign = map.get("sign");
		String openid = map.get("openid");
		Double total_fee = Double.valueOf(map.get("total_fee"));
		total_fee = total_fee/100;
		Date time_end = DateUtils.parseDate(map.get("time_end"));
		logger.warn("微信回调中返回的成功时间："+time_end);
		String attach = map.get("attach");
		JSONObject obj = JsonUtil.str2Obj(attach);
		String productType = null;
		String productId = null;
		String phone = null;
		double realPrice = 0;
		if(null != obj){
			productType = obj.getString("type");
			productId = obj.getString("pId");
			phone = obj.getString("uId");
			realPrice = obj.getDouble("price");  //购买会员卡实际买到的金额，比实际花的钱多
		}
		try {
			WxOrder wxOrderById = wxOrderService.getWxOrderById(transaction_id_own);
			if(wxOrderById.getStatus().equals(PayCommonUtil.PAYSUCCESS_STATUS)){
				return;
			}
			wxOrderById.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			wxOrderById.setPaysuctime(new Date());
			wxOrderById.setWxid(transaction_id);
			wxOrderById.setOpenid(openid);
			wxOrderById.setProductType(productType);
			wxOrderService.updateWxOrder(wxOrderById);
			if(Const.TTK.equals(productType)){ 
				//偷偷看成功后9件事：用户问题中间表插入数据；修改偷偷看的业务表状态;提问题人得到钱(得钱流水；公司支出流水)；回答问题人得钱(得钱流水；公司支出流水)；偷看人支出流水
				//updateAfterTTK(total_fee, time_end, productId);
				userDealRecordService.onLookRunning(phone, productId, PayTypeUtil.PAYTYPE_WEIXIN, total_fee);
				logger.warn("结束偷偷看业务");
			}else if(Const.XS.equals(productType)){
				//悬赏成功3件事：修改问题状态；用户支出流水；公司入账流水
				updateAfterXS(total_fee, time_end, productId);
				logger.warn("结束悬赏业务");
			}else if(Const.VIP.equals(productType)){
				//购买会员卡成功：修改会员卡业务状态；用户支出流水；公司入账流水；公司支出流水；会员卡入账流水
				updateAfterVIP(total_fee, time_end, productId, realPrice);
				logger.warn("结束会员卡购买业务");
			}else if(Const.REDBAG.equals(productType)){
				//修改红包业务表状态；发红包人支付流水；公司入账流水；公司出账流水；用户余额增加；用户余额增加流水；发短信通知收红包人
				updateAfterRedBag(total_fee, time_end, productId);
				logger.warn("结束发红包业务");
			}else if(Const.WISH.equals(productType)){
				//修改购买愿望表业务状态；许愿人支付流水；公司入账流水
				updateAfterWish(total_fee, time_end, productId);
				logger.warn("结束许愿业务");
			}else if(Const.VEDIO.equals(productType)){
				//用户视频中间表插入数据；用户支付流水；公司入账流水
				updateAfterVedio(total_fee, time_end, productId);
				logger.warn("结束视频购买业务");
			}else if(Const.ADDXS.equals(productType)){
				questionService.updateUserAndQuestionAndOrCompany(null, phone, total_fee.intValue(), productId, "weixin");
				logger.warn("结束加赏支付业务");
			}else if(Const.ZX.equals(productType)){
				userDealRecordService.updateAdviosyRunning(phone, productId, PayTypeUtil.PAYTYPE_WEIXIN, total_fee);
				logger.warn("结束咨询支付业务");
			}else if(PayTypeUtil.GOODSTYPE_VIDEO_SINGLE.equals(productType)){
				//videoBuyHistoryService.updatePaystatus(productId,PayCommonUtil.PAYSUCCESS_STATUS);
				userDealRecordService.videoRunning(phone, productId, PayTypeUtil.PAYTYPE_WEIXIN, total_fee);
				logger.warn("结束单个视频购买业务业务");
			}else if(PayTypeUtil.GOODSTYPE_VIDEO_CARD.equals(productType)){
				videoBuyHistoryService.updateVideocardBuy(productId);
				logger.warn("结束视频卡购买业务");
			}else{
				logger.error("productType参数未获取到");
			}
		} catch (Exception e) {
			logger.error("微信回调异常："+e);
			e.printStackTrace();
			WxOrder order = new WxOrder();
			order.setId(transaction_id_own);
			order.setStatus(PayCommonUtil.PAY_ERROR_CODE);
			order.setRemark("微信回调异常");
			wxOrderService.updateWxOrder(order);
		}
	}

	
	//微信退款回调
	public void refundWeixinBack(Map<String, String> map){
    	
    	String out_refund_no = map.get("out_refund_no");//商户退款单号
    	//String transaction_id = map.get("transaction_id");//微信订单号
    	String out_trade_no = map.get("out_trade_no");//商户订单号
    	//String refund_id = map.get("refund_id");//微信退款单号
    	String settlement_refund_fee = map.get("settlement_refund_fee");//退款金额
    	/**
    	 * SUCCESS-退款成功
			CHANGE-退款异常
			REFUNDCLOSE—退款关闭
    	 */
    	try {
			String refund_status = map.get("refund_status");//退款状态
			//String success_time = map.get("success_time");//退款成功时间
			String refund_recv_accout = map.get("refund_recv_accout");//退款入账账户
			String refund_account = map.get("refund_account");//退款资金来源
			String refund_request_source = map.get("refund_request_source");//退款发起来源
			WxRefund bsbWxRefund = new WxRefund();
			bsbWxRefund.setUuid(out_refund_no);
			bsbWxRefund.setRefund_account(refund_account);
			bsbWxRefund.setRefund_recv_accout(refund_recv_accout);
			bsbWxRefund.setRefund_request_source(refund_request_source);
			Integer valueOf = Integer.valueOf(settlement_refund_fee);
			bsbWxRefund.setSettlement_refund_fee(valueOf);
			WxOrder bsbWxOrder = wxOrderService.getWxOrderById(out_trade_no);
			if(refund_status.equals("SUCCESS")){
				bsbWxRefund.setRefund_status(PayCommonUtil.REFUND_STATUS_1);
				//pushService.push(PushType.MODEL_10, null, bsbWxOrder.getUserId(), PushType.ACTIVITY_1);
			}else if(refund_status.equals("CHANGE")){
				bsbWxRefund.setRefund_status(PayCommonUtil.REFUND_STATUS_3);
				bsbWxRefund.setErr_code_des("微信回调显示退款异常！");
				logger.info("微信回调显示退款异常！：" + JsonUtil.toJson(map));
			}else {
				bsbWxRefund.setRefund_status(PayCommonUtil.REFUND_STATUS_2);
				bsbWxRefund.setErr_code_des("微信回调显示退款关闭！");
				logger.info("微信回调显示退款关闭！：" + JsonUtil.toJson(map));
			}
			Date date = new Date();
			bsbWxRefund.setSuccess_time(date);
			WxRefundExample bsbWxRefundExample = new WxRefundExample();
			Criteria createCriteria = bsbWxRefundExample.createCriteria();
			
			createCriteria.andUuidEqualTo(out_refund_no);
			createCriteria.andRefund_statusNotEqualTo("1");
			
			if(bsbWxOrder==null){
				bsbWxRefund.setErr_code_des("微信回调商户订单号错误!");
				logger.info("微信回调商户订单号错误!：" + JsonUtil.toJson(map));
			}
			wxRefundService.chuliWxRefund(bsbWxRefund, bsbWxRefundExample);
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("微信退款回调失败：" + JsonUtil.toJson(map));
		}
    	
    }

  //查询退款
    
    public Object checkRefund(String refundId,String type){

    	BaseRes<Map<String, String>> res = new BaseRes<Map<String, String>>();
    	
    	try {
			if(StringUtils.isEmpty(refundId)){
				res.setCode(PayCommonUtil.FAIL_CODE);
				res.setDes("缺少订单号参数");
				return res;
			}
			SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();  
			if(StringUtils.isBlank(type)){
				parameterMap.put("refund_id", refundId);//退款微信订单号
			}else if(type.equals("0")){
				parameterMap.put("refund_id", refundId);
			}else if(type.equals("1")){
				parameterMap.put("transaction_id", refundId);;//微信订单号
			}else if (type.equals("2")) {
				parameterMap.put("out_trade_no", refundId);;//商户订单号
			}else if (type.equals("3")) {
				parameterMap.put("out_refund_no", refundId);;//商户退款单号
			}else {
				parameterMap.put("refund_id", refundId);//退款微信订单号
			}
			parameterMap.put("appid", PayCommonUtil.APPID);  
			parameterMap.put("mch_id", PayCommonUtil.MCH_ID);  
			
			parameterMap.put("nonce_str", randomString); 
			
			String sign = PayCommonUtil.createSign("UTF-8", parameterMap);
			parameterMap.put("sign", sign);  
			String requestXML = PayCommonUtil.getRequestXml(parameterMap);  
			logger.info("微信查询退款订单请求报文："+requestXML);  
			String result = PayCommonUtil.httpsRequest(PayCommonUtil.API_REFUND_CHECK_URL, "POST",  requestXML);  
			logger.info("微信查询退款订单返回报文"+result);  
			Map<String, String> map = null;  
			map = PayCommonUtil.doXMLParse(result);  
			String return_code  = map.get("return_code");
			String return_msg  = map.get("return_msg");
			String result_code  = map.get("result_code");
			String err_code = map.get("err_code");
			String err_code_des = map.get("err_code_des");
			//logger.info("微信查询订单json"+PayCommonUtil.toJson(map));
			if (return_code.equalsIgnoreCase(PayCommonUtil.SUCCESS)) {
				if (result_code.equalsIgnoreCase(PayCommonUtil.SUCCESS)) {
					res.setCode(BaseRes.SUCCESS_CODE);
					res.setDes(err_code_des);
					res.setData(map);
					/*String refund_id_0 = map.get("refund_id_0");
					String out_trade_no = map.get("out_trade_no");
					String transaction_id = map.get("transaction_id");
					String total_fee = map.get("total_fee");
					String cash_fee = map.get("cash_fee");
					String out_refund_no_0 = map.get("out_refund_no_0");
					String refund_fee_$n = map.get("refund_fee_$n");
					
					String refund_status_$n = map.get("refund_status_$n");
					String refund_recv_accout_$n = map.get("refund_recv_accout_$n");
					String refund_success_time_$n = map.get("refund_success_time_$n");*/
					logger.info("查询退款订单成功："+JsonUtil.toJson(map));
				}else{
					
					logger.info("查询退款订单失败："+"refundId:"+refundId+",result_code:"+result_code+",err_code:"+err_code+",err_code_des:"+err_code_des);
					res.setCode(BaseRes.FAIL_CODE);
					res.setDes(err_code_des);
				}
			}else{
				logger.info("微信查询退款订单通信异常:"+return_msg);
				res.setCode(BaseRes.FAIL_CODE);
				res.setDes(return_msg);
				
			}
		} catch (JDOMException e) {
			logger.error("JDOMException:xml解析异常");
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
		} catch (IOException e) {
			logger.error("IOException:解析异常");
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
		}
    	return res;
    
    }

	private void updateAfterVedio(Double total_fee, Date time_end,String productId) {
		logger.warn("开始购买视频业务");
		UserDrama userDramaById = userDramaService.getUserDramaById(productId);
		String userId = userDramaById.getUserId();
		userDramaById.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		//支付流水
		UserDealRecord userDealRecord = new UserDealRecord();
		userDealRecord.setUuid(UUIDGenerator.getUUID());
		userDealRecord.setCreateDate(new Date());
		userDealRecord.setBusinessNo(productId);
		userDealRecord.setAccountType(Const.ACCOUNTPERSON);
		userDealRecord.setSum(total_fee);
		userDealRecord.setGoodsType(PayTypeUtil.GOODSTYPE_VIDEOS);
		userDealRecord.setUserId(userId);
		userDealRecord.setPaySucTime(time_end);
		userDealRecord.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
		userDealRecord.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
		//公司入账流水
		UserDealRecord userDealRecord1 = new UserDealRecord();
		userDealRecord1.setUuid(UUIDGenerator.getUUID());
		userDealRecord1.setCreateDate(new Date());
		userDealRecord1.setBusinessNo(productId);
		userDealRecord1.setAccountType(Const.ACCOUNTCOMPANY);
		userDealRecord1.setSum(total_fee);
		userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_VIDEOS);
		userDealRecord1.setUserId(Const.JSBUSERID);
		userDealRecord1.setPaySucTime(time_end);
		userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
		userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
		userDramaService.updateAfterBuy(userDramaById,userDealRecord,userDealRecord1);
	}

	private void updateAfterWish(Double total_fee, Date time_end,String productId) {
		logger.warn("开始许愿业务");
		Wishbuy wishbuyById = wishbuyService.getWishbuyById(productId);
		Integer buyCount = wishbuyById.getBuyCount();
		String userId = wishbuyById.getUserId();
		String wishId = wishbuyById.getWishId();
		//许愿业务表状态
		Wishbuy wishbuy = new Wishbuy();
		wishbuy.setId(productId);
		wishbuy.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		//生成许愿号
		List<Wishcode> codeList = new ArrayList<Wishcode>();
		for (int i = 0; i < buyCount; i++) {
			Wishcode wishcode = new Wishcode();
			wishcode.setId(UUIDGenerator.getUUID());
			wishcode.setBuywithId(productId);
			wishcode.setUserId(userId);
			wishcode.setWishId(wishId);
			long val = redisService.getIncrby(wishId+"_code");
			if(val==0){
				val = System.currentTimeMillis();
			}
			String code = String.valueOf(val);
			wishcode.setCode(code);
			codeList.add(wishcode);
		}
		//许愿支付流水
		UserDealRecord userDealRecord = new UserDealRecord();
		userDealRecord.setUuid(UUIDGenerator.getUUID());
		userDealRecord.setCreateDate(new Date());
		userDealRecord.setBusinessNo(productId);
		userDealRecord.setAccountType(Const.ACCOUNTPERSON);
		userDealRecord.setSum(total_fee);
		userDealRecord.setGoodsType(PayTypeUtil.GOODSTYPE_WISHS);
		userDealRecord.setUserId(userId);
		userDealRecord.setPaySucTime(time_end);
		userDealRecord.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
		userDealRecord.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
		//公司入账流水
		UserDealRecord userDealRecord1 = new UserDealRecord();
		userDealRecord1.setUuid(UUIDGenerator.getUUID());
		userDealRecord1.setCreateDate(new Date());
		userDealRecord1.setBusinessNo(productId);
		userDealRecord1.setAccountType(Const.ACCOUNTCOMPANY);
		userDealRecord1.setSum(total_fee);
		userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_WISHS);
		userDealRecord1.setUserId(Const.JSBUSERID);
		userDealRecord1.setPaySucTime(time_end);
		userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
		userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
		wishbuyService.updateAfterWish(wishbuy,codeList,userDealRecord,userDealRecord1);
	}

	private void updateAfterRedBag(Double total_fee, Date time_end,
			String productId) {
		logger.warn("开始发红包业务");
		RedEnvelopes redEnvelopesByUuid = redEnvelopesService.getRedEnvelopesByUuid(productId);
		String sendPhoneNum = redEnvelopesByUuid.getSendPhoneNum();
		String userPhoneNum = redEnvelopesByUuid.getUserPhoneNum();
		String nameRecive = getUserRealName(userPhoneNum);
		String nameSend = getUserRealName(sendPhoneNum);
		//修改红包流水状态
		RedEnvelopes red = new RedEnvelopes();
		red.setUuid(productId);
		red.setRedStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		red.setReceiveDate(new Date());
		
		User user = new User();
		Double balance = getCurrenBalance(userPhoneNum);
		user.setPhoneNumber(userPhoneNum);
		user.setBalance(balance + total_fee);                      //增加余额
		//发红包支付流水
		UserDealRecord userDealRecord = new UserDealRecord();
		userDealRecord.setUuid(UUIDGenerator.getUUID());
		userDealRecord.setCreateDate(new Date());
		userDealRecord.setBusinessNo(productId);
		userDealRecord.setAccountType(Const.ACCOUNTPERSON);
		userDealRecord.setSum(total_fee);
		userDealRecord.setGoodsType(PayTypeUtil.GOODSTYPE_ENVELOPES);
		userDealRecord.setUserId(sendPhoneNum);
		userDealRecord.setPaySucTime(time_end);
		userDealRecord.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
		userDealRecord.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
		//用户微信发红包，公司收入流水
		UserDealRecord userDealRecord1 = new UserDealRecord();
		userDealRecord1.setUuid(UUIDGenerator.getUUID());
		userDealRecord1.setCreateDate(new Date());
		userDealRecord1.setBusinessNo(productId);
		userDealRecord1.setAccountType(Const.ACCOUNTCOMPANY);
		userDealRecord1.setSum(total_fee);
		userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_ENVELOPES);
		userDealRecord1.setUserId(Const.JSBUSERID);
		userDealRecord1.setPaySucTime(time_end);
		userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
		userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
		//公司支出
		UserDealRecord userDealRecord2 = new UserDealRecord();
		userDealRecord2.setUuid(UUIDGenerator.getUUID());
		userDealRecord2.setCreateDate(new Date());
		userDealRecord2.setBusinessNo(productId);
		userDealRecord2.setAccountType(Const.ACCOUNTCOMPANY);
		userDealRecord2.setSum(total_fee);
		userDealRecord2.setGoodsType(PayTypeUtil.GOODSTYPE_ENVELOPES);
		userDealRecord2.setUserId(Const.JSBUSERID);
		userDealRecord2.setPaySucTime(time_end);
		userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_COMPANYENVELOPES);
		userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord2.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
		//用户入账流水
		UserDealRecord userDealRecord3 = new UserDealRecord();
		userDealRecord3.setUuid(UUIDGenerator.getUUID());
		userDealRecord3.setCreateDate(new Date());
		userDealRecord3.setBusinessNo(productId);
		userDealRecord3.setAccountType(Const.ACCOUNTPERSON);
		userDealRecord3.setSum(total_fee);
		userDealRecord3.setGoodsType(PayTypeUtil.GOODSTYPE_ENVELOPES);
		userDealRecord3.setUserId(userPhoneNum);
		userDealRecord3.setPaySucTime(time_end);
		userDealRecord3.setPayType(PayTypeUtil.PAYTYPE_COMPANYENVELOPES);
		userDealRecord3.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord3.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
		redEnvelopesService.updateAfterSendRedbag(red,user,userDealRecord,userDealRecord1,userDealRecord2,userDealRecord3);
		//红包领取未操作时，用户余额不增加//修改为没有领取红包操作直接进入用户余额
		if(StringUtils.isNotEmpty(nameRecive)){
			try {
				Article articleById = articelService.getArticleById(redEnvelopesByUuid.getQuestionUuid());
				String str[] = new String[]{nameSend,String.valueOf(total_fee),articleById.getTitle()};
				User user2 = userService.getUserByPhoneNumber(userPhoneNum);
				if(user2 != null){
					smsSendService.sendNotify(SMSAPPID,user2.getPhone(), Const.SCENE_REDBAG_REWARD, str);
				}
				//通知栏推送
				String str_push[] = new String[]{redEnvelopesByUuid.getQuestionUuid(),nameSend,String.valueOf(total_fee),articleById.getTitle()};
				pushService.pushAlias(PushType.MODEL_3, str_push, userPhoneNum, "1");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void updateAfterVIP(Double total_fee, Date time_end,
			String productId, double realPrice) {
		logger.warn("开始发红包业务");
		PurchaseOrder purchaseOrderByUuid = purchaseOrderService.getPurchaseOrderByUuid(productId);
		String phoneNum = purchaseOrderByUuid.getPhoneNum();
		//修改VIP流水状态
		PurchaseOrder purchaseOrder = new PurchaseOrder();
		purchaseOrder.setUuid(productId);
		purchaseOrder.setPaymentStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		//增加用户VIP余额
		User userByPhone = userService.getUserByPhoneNumber(phoneNum);  
		Integer companyRole = userByPhone.getCompanyRole();
		IntegralService.integral(phoneNum, "recharge", (int)realPrice);
		if(Const.COMPANYDRIFT == companyRole){
			User user = new User();
			//Double vipBalance = userByPhone.getVipBalance();   //当前余额
			user.setPhoneNumber(phoneNum);
			user.setVipBalance(realPrice);   //增加余额
			//支付流水
			UserDealRecord userDealRecord = new UserDealRecord();
			userDealRecord.setUuid(UUIDGenerator.getUUID());
			userDealRecord.setCreateDate(new Date());
			userDealRecord.setBusinessNo(productId);
			userDealRecord.setAccountType(Const.ACCOUNTPERSON);
			userDealRecord.setSum(total_fee);
			userDealRecord.setGoodsType(PayTypeUtil.GOODSTYPE_VIPCARD);
			userDealRecord.setUserId(phoneNum);
			userDealRecord.setPaySucTime(time_end);
			userDealRecord.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
			userDealRecord.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
			userDealRecord.setRealPrice(realPrice);
			//公司入账流水
			UserDealRecord userDealRecord3 = new UserDealRecord();
			userDealRecord3.setUuid(UUIDGenerator.getUUID());
			userDealRecord3.setCreateDate(new Date());
			userDealRecord3.setBusinessNo(productId);
			userDealRecord3.setAccountType(Const.ACCOUNTCOMPANY);
			userDealRecord3.setSum(total_fee);
			userDealRecord3.setGoodsType(PayTypeUtil.GOODSTYPE_VIPCARD);
			userDealRecord3.setUserId(Const.JSBUSERID);
			userDealRecord3.setPaySucTime(time_end);
			userDealRecord3.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
			userDealRecord3.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord3.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
			userDealRecord3.setRealPrice(realPrice);
			//会员卡入账流水
			UserDealRecord userDealRecord1 = new UserDealRecord();
			userDealRecord1.setUuid(UUIDGenerator.getUUID());
			userDealRecord1.setCreateDate(new Date());
			userDealRecord1.setBusinessNo(productId);
			userDealRecord1.setAccountType(Const.ACCOUNTPERSON);
			userDealRecord1.setSum(realPrice);
			userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_VIPCARD);
			userDealRecord1.setUserId(phoneNum);
			userDealRecord1.setPaySucTime(new Date());
			userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_VIPBALANCE);
			userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
			//公司支出流水
			UserDealRecord userDealRecord2 = new UserDealRecord();
			userDealRecord2.setUuid(UUIDGenerator.getUUID());
			userDealRecord2.setCreateDate(new Date());
			userDealRecord2.setBusinessNo(productId);
			userDealRecord2.setAccountType(Const.ACCOUNTPERSON);
			userDealRecord2.setSum(realPrice);
			userDealRecord2.setGoodsType(PayTypeUtil.GOODSTYPE_VIPCARD);
			userDealRecord2.setUserId(Const.JSBUSERID);
			userDealRecord2.setPaySucTime(new Date());
			userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_COMPANYENVELOPES);
			userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord2.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
			purchaseOrderService.updateUserAfterBuyVip(purchaseOrder,user,userDealRecord,userDealRecord1,userDealRecord2,userDealRecord3);
		}else if(Const.COMPANYADMIN == companyRole || Const.COMPANYGENERAL == companyRole){
			Company com = new Company();
			String companyUuid = userByPhone.getCompanyUuid();
			Company companyByUuid = companyService.getCompanyByUuid(companyUuid);
			Double businessBalance = companyByUuid.getBusinessBalance();
			com.setUuid(companyUuid);
			com.setBusinessBalance(businessBalance + realPrice);
			//支出
			UserDealRecord userDealRecord = new UserDealRecord();
			userDealRecord.setUuid(UUIDGenerator.getUUID());
			userDealRecord.setCreateDate(new Date());
			userDealRecord.setBusinessNo(productId);
			userDealRecord.setAccountType(Const.ACCOUNTPERSON);
			userDealRecord.setSum(total_fee);
			userDealRecord.setGoodsType(PayTypeUtil.GOODSTYPE_VIPCARD);
			userDealRecord.setUserId(phoneNum);
			userDealRecord.setPaySucTime(time_end);
			userDealRecord.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
			userDealRecord.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
			userDealRecord.setRealPrice(realPrice);
			//公司入账流水
			UserDealRecord userDealRecord3 = new UserDealRecord();
			userDealRecord3.setUuid(UUIDGenerator.getUUID());
			userDealRecord3.setCreateDate(new Date());
			userDealRecord3.setBusinessNo(productId);
			userDealRecord3.setAccountType(Const.ACCOUNTCOMPANY);
			userDealRecord3.setSum(total_fee);
			userDealRecord3.setGoodsType(PayTypeUtil.GOODSTYPE_VIPCARD);
			userDealRecord3.setUserId(Const.JSBUSERID);
			userDealRecord3.setPaySucTime(time_end);
			userDealRecord3.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
			userDealRecord3.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord3.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
			userDealRecord3.setRealPrice(realPrice);
			//会员卡入账流水
			UserDealRecord userDealRecord1 = new UserDealRecord();
			userDealRecord1.setUuid(UUIDGenerator.getUUID());
			userDealRecord1.setCreateDate(new Date());
			userDealRecord1.setBusinessNo(productId);
			userDealRecord1.setAccountType(Const.ACCOUNTCOMPANY);
			userDealRecord1.setSum(realPrice);
			userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_VIPCARD);
			userDealRecord1.setUserId(companyUuid);                    //购买公司会员卡金额加入公司账户，此处用户id保存公司ID
			userDealRecord1.setPaySucTime(new Date());
			userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_VIPBALANCE);
			userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
			//公司支出流水
			UserDealRecord userDealRecord2 = new UserDealRecord();
			userDealRecord2.setUuid(UUIDGenerator.getUUID());
			userDealRecord2.setCreateDate(new Date());
			userDealRecord2.setBusinessNo(productId);
			userDealRecord2.setAccountType(Const.ACCOUNTPERSON);
			userDealRecord2.setSum(realPrice);
			userDealRecord2.setGoodsType(PayTypeUtil.GOODSTYPE_VIPCARD);
			userDealRecord2.setUserId(Const.JSBUSERID);
			userDealRecord2.setPaySucTime(new Date());
			userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_COMPANYENVELOPES);
			userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord2.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
			purchaseOrderService.updateCompanyAfterBuyVip(purchaseOrder, com,userDealRecord,userDealRecord1,userDealRecord2,userDealRecord3);
		}else{
			logger.error("购买会员卡成功后数据异常，companyRole = "+companyRole);
		}
	}

	private void updateAfterXS(Double total_fee, Date time_end, String productId) {
		logger.warn("开始悬赏业务");
		Question questionByUuid = questionService.getQuestionByUuid(productId);
		String phoneNum = questionByUuid.getPhoneNum();

		//用户增加积分
		IntegralService.integral(phoneNum, "question", 5);
		Question question = new Question();
		question.setUuid(productId);
		question.setPayStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		//用户支出
		UserDealRecord userDealRecord = new UserDealRecord();
		userDealRecord.setUuid(UUIDGenerator.getUUID());
		userDealRecord.setCreateDate(new Date());
		userDealRecord.setBusinessNo(productId);
		userDealRecord.setAccountType(Const.ACCOUNTPERSON);
		userDealRecord.setSum(total_fee);
		userDealRecord.setGoodsType(PayTypeUtil.GOODSTYPE_REWARD);
		userDealRecord.setUserId(phoneNum);
		userDealRecord.setPaySucTime(time_end);
		userDealRecord.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
		userDealRecord.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
		//公司收入
		UserDealRecord userDealRecord1 = new UserDealRecord();
		userDealRecord1.setUuid(UUIDGenerator.getUUID());
		userDealRecord1.setCreateDate(new Date());
		userDealRecord1.setBusinessNo(productId);
		userDealRecord1.setAccountType(Const.ACCOUNTCOMPANY);
		userDealRecord1.setSum(total_fee);
		userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_REWARD);
		userDealRecord1.setUserId(Const.JSBUSERID);
		userDealRecord1.setPaySucTime(time_end);
		userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
		userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
		questionService.updateAfterXS(question,userDealRecord ,userDealRecord1);
	}

	@SuppressWarnings("unused")
	private void updateAfterTTK(Double total_fee, Date time_end,
			String productId) {
		logger.warn("开始偷偷看业务");
		Secretly secretlyByUuid = secretlyService.getSecretlyByUuid(productId);
		String questionUuid = secretlyByUuid.getQuestionUuid();					// 问题uuid
		String answerUuid = secretlyByUuid.getAnswerUuid();                       //答案uuid
		String mentionPhoneNum = secretlyByUuid.getMentionPhoneNum();            //提问题人手机号
		String peepPhoneNum = secretlyByUuid.getPeepPhoneNum();                  //偷看者的手机号
		
		double sumMoneyUser = secretlyService.getSumMoneyUser(mentionPhoneNum, questionUuid);
		Question question = questionService.getQuestionByUuid(questionUuid);
		double tatalMoney=0;
		if(question!=null){
			Integer addMoney = question.getAddMoney();
			Integer money = question.getMoney();
			if(addMoney!=null){
				tatalMoney=money+addMoney;	
			}else {
				tatalMoney=money;
			}
		}
		//用户问题中间表插入数据
		QuestionUserKey record = new QuestionUserKey();
		record.setPhoneNumber(peepPhoneNum);
		record.setQuestionUuid(questionUuid);
		//提问题人得到钱
		Double balance = getCurrenBalance(mentionPhoneNum);
		User user = new User();
		user.setPhoneNumber(mentionPhoneNum);
		double ttkAsk = RewardUtil.TTKAsk(total_fee);
		user.setBalance(balance + ttkAsk);
		//回答问题人得钱
		Answer answerByUuid = answerService.getAnswerByUuid(answerUuid);
		String phoneNumber = answerByUuid.getPhoneNumber();
		Double currenBalance = getCurrenBalance(phoneNumber);
		User answerUser = new User();
		answerUser.setPhoneNumber(phoneNumber);
		double ttkAnswer = RewardUtil.TTKAnswer(total_fee);
		answerUser.setBalance(currenBalance +ttkAnswer);
		
		//TTK业务表修改状态为成功
		Secretly secretly = new Secretly();
		secretly.setUuid(productId);
		secretly.setPayStatus(PayCommonUtil.SUCCESS_CODE);
		//偷看人支出流水
		UserDealRecord userDealRecord = new UserDealRecord();
		userDealRecord.setUuid(UUIDGenerator.getUUID());
		userDealRecord.setCreateDate(new Date());
		userDealRecord.setBusinessNo(productId);
		userDealRecord.setAccountType(Const.ACCOUNTPERSON);
		userDealRecord.setSum(total_fee);
		userDealRecord.setGoodsType(PayTypeUtil.GOODSTYPE_SECRETLY);
		userDealRecord.setUserId(peepPhoneNum);
		userDealRecord.setPaySucTime(time_end);
		userDealRecord.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
		userDealRecord.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
		//公司入账流水
		UserDealRecord userDealRecord1 = new UserDealRecord();
		userDealRecord1.setUuid(UUIDGenerator.getUUID());
		userDealRecord1.setCreateDate(new Date());
		userDealRecord1.setBusinessNo(productId);
		userDealRecord1.setAccountType(Const.ACCOUNTCOMPANY);
		userDealRecord1.setSum(total_fee);
		userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_SECRETLY);
		userDealRecord1.setUserId(Const.JSBUSERID);
		userDealRecord1.setPaySucTime(time_end);
		userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
		userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
		//公司支出流水
		UserDealRecord userDealRecord2 = new UserDealRecord();
		userDealRecord2.setUuid(UUIDGenerator.getUUID());
		userDealRecord2.setCreateDate(new Date());
		userDealRecord2.setBusinessNo(productId);
		userDealRecord2.setAccountType(Const.ACCOUNTCOMPANY);
		double ttkJsb = RewardUtil.TTKJsbExpenditure(total_fee);   //公司支出钱
		userDealRecord2.setSum(ttkJsb);
		userDealRecord2.setGoodsType(PayTypeUtil.GOODSTYPE_SECRETLY);
		userDealRecord2.setUserId(Const.JSBUSERID);
		userDealRecord2.setPaySucTime(time_end);
		userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_COMPANYENVELOPES);
		userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord2.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
		//提问题人入账流水
		UserDealRecord userDealRecord4 = new UserDealRecord();
		userDealRecord4.setUuid(UUIDGenerator.getUUID());
		userDealRecord4.setCreateDate(new Date());
		userDealRecord4.setBusinessNo(productId);
		userDealRecord4.setAccountType(Const.ACCOUNTPERSON);
		userDealRecord4.setSum(ttkAsk);
		userDealRecord4.setGoodsType(PayTypeUtil.GOODSTYPE_SECRETLY);
		userDealRecord4.setUserId(mentionPhoneNum);
		userDealRecord4.setPaySucTime(new Date());
		userDealRecord4.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
		userDealRecord4.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord4.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
		//回答问题人入账流水
		UserDealRecord userDealRecord5 = new UserDealRecord();
		userDealRecord5.setUuid(UUIDGenerator.getUUID());
		userDealRecord5.setCreateDate(new Date());
		userDealRecord5.setBusinessNo(productId);
		userDealRecord5.setAccountType(Const.ACCOUNTPERSON);
		userDealRecord5.setSum(ttkAnswer);
		userDealRecord5.setGoodsType(PayTypeUtil.GOODSTYPE_SECRETLY);
		userDealRecord5.setUserId(phoneNumber);
		userDealRecord5.setPaySucTime(new Date());
		userDealRecord5.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
		userDealRecord5.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
		userDealRecord5.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
		if(sumMoneyUser>=tatalMoney*2){
			//提问者 回答者 不分钱 不计流水， 公司不计支出 支出流水
			questionService.updateAfterTTK(record,null,null,secretly,userDealRecord,userDealRecord1,null,null,null);
		}else {
			
			questionService.updateAfterTTK(record,user,answerUser,secretly,userDealRecord,userDealRecord1,userDealRecord2,userDealRecord4,userDealRecord5);
		}
	}


	private String getUserRealName(String userPhoneNum) {
		User userRevice = userService.getUserByPhoneNumber(userPhoneNum);
		String nameRecive = userRevice.getRealName();
		return nameRecive;
	}


	private Double getCurrenBalance(String mentionPhoneNum) {
		User userByPhoneNumber = userService.getUserByPhoneNumber(mentionPhoneNum);
		Double balance = userByPhoneNumber.getBalance();
		return balance;
	}
	/**
	 * 两次提现间隔是否大于限制时间
	 * @param phone
	 * @return
	 */
	private boolean isWithDraw(String phone){
		List<Withdraw> lastRecord = withdrawService.getLastRecord(phone);
		if(null!=lastRecord&&lastRecord.size()>0){
			Withdraw withdraw = lastRecord.get(0);
			Date createDate = withdraw.getCreateDate();
			logger.warn("上次提现时间："+DateUtils.formatDateTime(createDate));
			long pastDays = DateUtils.pastDays(createDate);
			logger.warn("过去天数："+pastDays);
			if(pastDays > Const.TIME){
				return true;
			}
			return false;
		}
		return true;
	}

	/**
	 * 企业支付
	 * @param user 
	 * @param wxEnterpriseReq
	 * @param request
	 */
	@SuppressWarnings("unchecked")
	public WxEnterpriseRes updatePayEnterprise(User user, WxEnterpriseReq wxEnterpriseReq,HttpServletRequest request) {
		WxEnterpriseRes res = new WxEnterpriseRes();
		//提现条件判断
		Double balance = user.getBalance();
		String phone = user.getPhoneNumber();
		if(!WithdrawUtil.isAgree(balance)){
			res.setCode(PayCommonUtil.FAIL_CODE);
			res.setDes("余额不足，未达到提现要求！");
			return res;
		}
		double amount = wxEnterpriseReq.getMoney()==0?balance:wxEnterpriseReq.getMoney();
		String code = wxEnterpriseReq.getCode();
		String openid = coreService.getOpenId(code, WeiXinPublicUtil.SRCAPP);
	//	String openid = "ojFD0v2kL8fGNdJUXVck5Iyfx4P8";    //测试用
		logger.info("获取到的openid："+openid);
		if(StringUtils.isEmpty(openid)){
			res.setCode(PayCommonUtil.FAIL_CODE);
			res.setDes("系统繁忙");
			return res;
		}
		String desc = wxEnterpriseReq.getDesc();
		if(amount < 1){
			res.setCode(PayCommonUtil.FAIL_CODE);
			res.setDes("支付金额不能小于最低限额1");
			return res;
		}
		if(amount > balance){
			res.setCode(PayCommonUtil.FAIL_CODE);
			res.setDes("余额不足");
			return res;
		}
		if(!isWithDraw(phone)){
			res.setCode(PayCommonUtil.FAIL_CODE);
			res.setDes("两次提现间隔时间须大于"+Const.TIME+"天");
			return res;
		}
		if(StringUtils.isEmpty(code)){
			res.setCode(PayCommonUtil.FAIL_CODE);
			res.setDes("系统繁忙");
			return res;
		}
		String sn = UUIDGenerator.getUUID();// 商户订单号
		double balanc = balance - amount;
		//减去用户余额生成提现流水
		String phoneNumber = user.getPhoneNumber();
		try {
			String remoteAddr = NetworkUtil.getIpAddress(request).equals("0:0:0:0:0:0:0:1")?"127.0.0.1":NetworkUtil.getIpAddress(request);
			updateUserWithdraw(user, balanc, amount, openid, sn,remoteAddr);
			if(amount <= Const.CHECKMONEY){    //提现金额小于等于审核限制金额是直接到账
				if(StringUtils.isEmpty(desc)){
					desc = "解税宝微信提现";
				}
				BigDecimal totalAmount = new BigDecimal( amount);
				SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
				parameterMap.put("mch_appid", PayCommonUtil.APPID);
				parameterMap.put("mchid", PayCommonUtil.MCH_ID);
				parameterMap.put("nonce_str", randomString);
				parameterMap.put("partner_trade_no", sn);
				parameterMap.put("openid", openid);
				BigDecimal total = totalAmount.multiply(new BigDecimal(100));
				java.text.DecimalFormat df = new java.text.DecimalFormat("0");
				parameterMap.put("amount", df.format(total));
//				parameterMap.put("check_name", "NO_CHECK");
				parameterMap.put("check_name", "FORCE_CHECK");
				parameterMap.put("re_user_name", "yy");
				parameterMap.put("desc", desc);
				parameterMap.put("spbill_create_ip","60.205.84.1");
				
				String sign = PayCommonUtil.createSign("UTF-8", parameterMap);
				parameterMap.put("sign", sign);
				
				String requestXML = PayCommonUtil.getRequestXml(parameterMap);
				logger.info("微信企业支付请求报文：" + requestXML);
				String result = PayCommonUtil.httpsRequestEnterprise(PayCommonUtil.ENTERPRISE_PAY_URL, requestXML);
				logger.info("企业支付返回报文："+result);
				Map<String,String> map = PayCommonUtil.doXMLParse(result);
				String return_code = map.get("return_code");
				String result_code = map.get("result_code");
				String partner_trade_no = map.get("partner_trade_no");
				String payment_no = map.get("payment_no");
				String payment_time = map.get("payment_time");
				
				if (return_code.equalsIgnoreCase(PayCommonUtil.SUCCESS)) {
					if (result_code.equalsIgnoreCase(PayCommonUtil.SUCCESS)) {  
						//修改提现表状态
						Withdraw withdraw = new Withdraw();
						withdraw.setUuid(partner_trade_no);
						withdraw.setWxid(payment_no);
						withdraw.setSucDate(DateUtils.parseDate(payment_time));
						withdraw.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
						withdrawService.updateWithdraw(withdraw);
						res.setCode(PayCommonUtil.SUCCESS_CODE);
						res.setDes("提现成功");
						return res;
					}else{
						String err_code = map.get("err_code");
						String err_code_des = map.get("err_code_des");
						Withdraw withdraw = new Withdraw();
						withdraw.setUuid(sn);
						withdraw.setErrorCode(err_code);
						withdraw.setReason(err_code_des);
						withdrawService.updateWithdraw(withdraw);  //保存微信返回错误信息
						logger.warn("保存微信返回错误信息："+JsonUtil.toJson(withdraw));
						
						
						refund(balance, sn, phoneNumber);
						logger.warn("调用微信企业支付：err_code"+err_code+",err_code_des"+err_code_des);
						res.setCode(PayCommonUtil.FAIL_CODE);
						res.setDes("提现失败，请联系管理员");
						return res;
					}
				}else {
					Withdraw withdraw = new Withdraw();
					withdraw.setUuid(partner_trade_no);
					withdraw.setStatus(PayCommonUtil.PENDING_QUERY_CODE);
					withdraw.setReason("网络错误，待查询");
					withdrawService.updateWithdraw(withdraw);  //记录网络错误后的待查询状态
					//TODO  可能网络出现错误，查询支付结果    线程池中查询支付结果
					this.taskExecutor.execute(new EnterpriseQueryTask(partner_trade_no));  
					res.setCode(PayCommonUtil.FAIL_CODE);
					res.setDes("系统繁忙");
					logger.error("调用微信企业付款通信异常");
					return res;
				}
			}else{
				res.setCode(PayCommonUtil.SUCCESS_CODE);
				res.setDes("提现成功,审核中!");
				return res;
			}
		} catch (Exception e) {
			refund(balance, sn, phoneNumber);
			logger.warn("调用微信企业支付：,err_code_des"+e);
			res.setCode(PayCommonUtil.FAIL_CODE);
			res.setDes("提现失败，请联系管理员");
			return res;
		}
	}
	/**
	 * 提现失败退回余额
	 * @param balance   提现钱余额
	 * @param sn        订单号
	 * @param phoneNumber   手机号
	 */
	private void refund(Double balance, String sn, String phoneNumber) {
		User user1 = new User();
		user1.setPhoneNumber(phoneNumber);
		user1.setBalance(balance);
		Withdraw withdraw1 = new Withdraw();
		withdraw1.setUuid(sn);
		withdraw1.setStatus(PayCommonUtil.ALREADY_REFUND_CODE);
		userService.updateUser(user1);//退回余额
		logger.warn("提现失败退回余额："+JsonUtil.toJson(user1));
		withdrawService.updateWithdraw(withdraw1);//记录退回操作
		logger.warn("记录退回操作："+JsonUtil.toJson(withdraw1));
	}
	/**
	 * 减去用户余额生成提现流水
	 * @param user    当前用户
	 * @param balance  余额
	 * @param amount   提现金额
	 * @param openid    openid
	 * @param sn        订单号
	 * @param remoteAddr 
	 */
	public void updateUserWithdraw(User user ,double balance,double amount,String openid,String sn, String remoteAddr){
		//减去用户余额
		User u = new User();
		u.setPhoneNumber(user.getPhoneNumber());
		u.setBalance(balance);
		logger.warn("提现减去用户余额："+JsonUtil.toJson(u));
		userService.updateUser(u);
		//生成提现流水
		Withdraw withdraw = new Withdraw();
		withdraw.setUuid(sn);
		withdraw.setCreateDate(new Date());
		withdraw.setMoney(amount);
		withdraw.setName(user.getUserName());
		withdraw.setOpenid(openid);
		withdraw.setPhoneNum(user.getPhoneNumber());
		withdraw.setStatus(PayCommonUtil.PAYPENDING_STATUS);
		withdraw.setAccountType("wx");
		withdraw.setIp(remoteAddr);
		withdrawService.addWithdraw(withdraw);
//		try {
//		} catch (Exception e) {
//			logger.error("企业提现生成订单异常："+e);
//		}
	}
	
	/**
	 * 企业支付订单查询
	 * @param partner_trade_no2 
	 * @param wxEnterpriseReq
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public WxEnterpriseRes enterpriseOrder(String partner_trade_no) {
		WxEnterpriseRes res = new WxEnterpriseRes();
		if(StringUtils.isEmpty(partner_trade_no)){
			res.setCode(PayCommonUtil.FAIL_CODE);
			res.setDes("商户订单号不能为空");
			logger.info("企业支付订单查询时订单号为空 partner_trade_no"+partner_trade_no);
			return res;
		}
		SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
		parameterMap.put("nonce_str", randomString);
		parameterMap.put("partner_trade_no", partner_trade_no);
		parameterMap.put("mch_id", PayCommonUtil.MCH_ID);
		parameterMap.put("appid", PayCommonUtil.APPID);
		
		String sign = PayCommonUtil.createSign("UTF-8", parameterMap);
		parameterMap.put("sign", sign);
		
		String requestXML = PayCommonUtil.getRequestXml(parameterMap);
		try {
			String result = PayCommonUtil.httpsRequestEnterprise(PayCommonUtil.ENTERPRISE_ORDER_URL, requestXML);
			logger.info("企业付款查询订单返回报文："+result);
			Map<String,String> map = PayCommonUtil.doXMLParse(result);
			String return_code = map.get("return_code");
			String result_code = map.get("result_code");
//			String mch_id = map.get("mch_id");
			//调用企业付款API时，微信系统内部产生的单号
			String detail_id = map.get("detail_id");
			String status = map.get("status");
			String reason = map.get("reason");
//			String openid = map.get("openid");   //转账的openid
//			String transfer_name = map.get("transfer_name");   //收款用户姓名
//			String payment_amount = map.get("payment_amount");  //付款金额单位分）
//			String transfer_time = map.get("transfer_time");    //发起转账的时间
//			String desc = map.get("desc");                      //付款时候的描述
			if (return_code.equalsIgnoreCase(PayCommonUtil.SUCCESS)) {
				if (result_code.equalsIgnoreCase(PayCommonUtil.SUCCESS)) { 
					if(status.equalsIgnoreCase(PayCommonUtil.SUCCESS)){
						Withdraw withdraw = new Withdraw();
						withdraw.setUuid(partner_trade_no);
						withdraw.setWxid(detail_id);
						withdraw.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
						withdrawService.updateWithdraw(withdraw);
						
					}else{    //FAILED:转账失败   PROCESSING:处理中
						logger.info("调用微信企业支付查询订单接口：status"+status+",reason"+reason);
//						Withdraw withdraw = new Withdraw();
//						withdraw.setUuid(partner_trade_no);
//						withdraw.setWxid(detail_id);
////						withdraw.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
//						withdraw.setErrorCode(status);
//						withdraw.setReason(reason);
//						withdrawService.updateWithdraw(withdraw);
					}
				}else{
					String err_code = map.get("err_code");
					String err_code_des = map.get("err_code_des");
					logger.info("调用微信企业支付查询订单接口：err_code"+err_code+",err_code_des"+err_code_des);
				}
			}else{
				logger.error("调用微信企业付款查询订单接口通信异常");
			}
		} catch (Exception e) {
			logger.error(e);
			res.setCode(PayCommonUtil.FAIL_CODE);
			res.setDes("调用微信企业付款查询订单接口异常");
		}
		return res;
	}
	
	class EnterpriseQueryTask implements Runnable{
		String partner_trade_no;
		int n;
		public EnterpriseQueryTask(String partner_trade_no){
			this.partner_trade_no = partner_trade_no;
		}
		@Override
		public void run() {
			if(n>=3){
				enterpriseOrder(partner_trade_no);
				n++;
			}
		}
		
	}

	public WxQueryOrderRes queryOrder(String version,String src, String partner_trade_no) {
		WxQueryOrderRes res = new WxQueryOrderRes();
		WxPayOrderQueryResult queryOrder = null;
		try {
			if(WeiXinPublicUtil.SRCAPP.equals(src)){
					queryOrder = this.wxAppService.getPayService().queryOrder("", partner_trade_no);
			}else if(WeiXinPublicUtil.SRCMP.equals(src)){
					queryOrder = this.wxMpService.getPayService().queryOrder("", partner_trade_no);
			}else{
				res.setCode(PayCommonUtil.FAIL_CODE);
				res.setDes("系统繁忙");
				return res;
			}
			if(null!= queryOrder){
				String returnCode = queryOrder.getReturnCode();
				String returnMsg = queryOrder.getReturnMsg();
				String resultCode = queryOrder.getResultCode();
				String tradeState = queryOrder.getTradeState();
				if(returnCode.equalsIgnoreCase(PayCommonUtil.SUCCESS)){
					if (resultCode.equalsIgnoreCase(PayCommonUtil.SUCCESS)) { 
						if(tradeState.equalsIgnoreCase(PayCommonUtil.SUCCESS)){
							res.setCode(PayCommonUtil.SUCCESS_CODE);
							res.setDes("支付成功");
						}else if(tradeState.equalsIgnoreCase("REFUND")){
							res.setCode(WxQueryOrderRes.REFUND);
							res.setDes("转入退款");
						}else if(tradeState.equalsIgnoreCase("NOTPAY")){
							res.setCode(WxQueryOrderRes.NOTPAY);
							res.setDes("未支付");
						}else if(tradeState.equalsIgnoreCase("CLOSED")){
							res.setCode(WxQueryOrderRes.CLOSED);
							res.setDes("已关闭");
						}else if(tradeState.equalsIgnoreCase("REVOKED")){
							res.setCode(WxQueryOrderRes.REVOKED);
							res.setDes("已撤销（刷卡支付）");
						}else if(tradeState.equalsIgnoreCase("USERPAYING")){
							res.setCode(WxQueryOrderRes.USERPAYING);
							res.setDes("用户支付中");
						}else if(tradeState.equalsIgnoreCase("PAYERROR")){
							res.setCode(WxQueryOrderRes.PAYERROR);
							res.setDes("支付失败(其他原因，如银行返回失败)");
						}
						return res;
					}else{
						String errCode = queryOrder.getErrCode();
						String errCodeDes = queryOrder.getErrCodeDes();
						logger.error("调用微信支付查询订单接口：err_code:"+errCode+",err_code_des:"+errCodeDes);
						res.setCode(PayCommonUtil.FAIL_CODE);
						res.setDes("系统繁忙");
					}
				}else{
					logger.error("微信支付查询订单接口通信异常resultCode:"+resultCode+",returnMsg:"+returnMsg);
					res.setCode(PayCommonUtil.FAIL_CODE);
					res.setDes("系统繁忙");
				}
			}else{
				res.setCode(PayCommonUtil.FAIL_CODE);
				res.setDes("系统繁忙");
			}
		} catch (WxErrorException e) {
			e.printStackTrace();
			logger.error("微信支付查询订单接口通信异常:"+e.getMessage().toString());
			res.setCode(PayCommonUtil.FAIL_CODE);
			res.setDes("系统繁忙");
		}
		return res;
	}
/**
 * 提现  V1.0
 * @param user
 * @param wxEnterpriseReq
 * @param request
 * @return
 */
	public WxEnterpriseRes updatePayPersonal(User user,WxEnterpriseReq wxEnterpriseReq, HttpServletRequest request) {
		WxEnterpriseRes res = new WxEnterpriseRes();
		String sn = UUIDGenerator.getUUID();// 商户订单号
		//提现条件判断
		Double balance = user.getBalance();
		String phone = user.getPhoneNumber();
		if(!WithdrawUtil.isAgree(balance)){
			res.setCode(PayCommonUtil.FAIL_CODE);
			res.setDes("最低提现金额为20元哦！");
			return res;
		}
		try {
			double amount = wxEnterpriseReq.getMoney()==0?balance:wxEnterpriseReq.getMoney();
			String code = wxEnterpriseReq.getCode();
	//		String openid = coreService.getOpenId(code, WeiXinPublicUtil.SRCAPP);
			WxMpUser userInfo = coreService.getUserInfo(code, "zh_CN", WeiXinPublicUtil.SRCAPP);
			logger.warn("获取到的用户信息："+JsonUtil.toJson(userInfo));
			String openid = userInfo.getOpenId();
		//	String openid = "ojFD0v2kL8fGNdJUXVck5Iyfx4P8";    //测试用
			logger.warn("获取到的openid："+openid);
			if(StringUtils.isEmpty(openid)){
				res.setCode(PayCommonUtil.FAIL_CODE);
				res.setDes("系统繁忙");
				return res;
			}
			String desc = wxEnterpriseReq.getDesc();
			if(amount < 1){
				res.setCode(PayCommonUtil.FAIL_CODE);
				res.setDes("支付金额不能小于最低限额1");
				return res;
			}
			if(amount > balance){
				res.setCode(PayCommonUtil.FAIL_CODE);
				res.setDes("余额不足");
				return res;
			}
			
			if(!isWithDraw(phone)){
				List<Withdraw> lastRecord = withdrawService.getLastRecord(phone);
				Withdraw withdraw = lastRecord.get(0);
				Date createDate = withdraw.getCreateDate();
				String formatDate = DateUtils.formatDate(createDate, "yyyy-MM-dd");
				res.setCode(PayCommonUtil.FAIL_CODE);
				res.setDes("两次提现间隔时间须大于"+Const.TIME+"天,您上次提现时间为"+formatDate);
				return res;
			}
			UserWx userWxById = userWxService.getUserWxByUserId(phone);
			boolean flag = false;
			if(null != userWxById){
				flag = true;
				String openId = userWxById.getOpenId();
				if(!openid.equals(openId)){
					res.setCode(PayCommonUtil.FAIL_CODE);
					res.setDes("该手机号已绑定其他微信，不能提现到此微信");
					return res;
				}
			}
			UserWxExample ex = new UserWxExample();
			com.jieshuibao.model.db.UserWxExample.Criteria criteria = ex.createCriteria();
			criteria.andOpenIdEqualTo(openid);
			List<UserWx> userWxs = userWxService.selectByExample(ex);
			if(null != userWxs && userWxs.size()>0){
				if(!userWxs.get(0).getUserId().equals(phone)){
					res.setCode(PayCommonUtil.FAIL_CODE);
					res.setDes("该微信已绑定其他手机号，不能提现到此微信");
					return res;
				}
			}
			double balanc = balance - amount;
			//减去用户余额生成提现流水
		
			String remoteAddr = NetworkUtil.getIpAddress(request).equals("0:0:0:0:0:0:0:1")?"127.0.0.1":NetworkUtil.getIpAddress(request);
			updateUserWithdraw(user, balanc, amount, openid, sn,remoteAddr);
			if(amount <= Const.CHECKMONEY){    //提现金额小于等于审核限制金额是直接到账
				if(StringUtils.isEmpty(desc)){
					desc = "航信办税宝微信提现";
				}
				BigDecimal totalAmount = new BigDecimal( amount);
				SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
				parameterMap.put("mch_appid", PayCommonUtil.APPID);
				parameterMap.put("mchid", PayCommonUtil.MCH_ID);
				parameterMap.put("nonce_str", randomString);
				parameterMap.put("partner_trade_no", sn);
				parameterMap.put("openid", openid);
				BigDecimal total = totalAmount.multiply(new BigDecimal(100));
				java.text.DecimalFormat df = new java.text.DecimalFormat("0");
				parameterMap.put("amount", df.format(total));
//				parameterMap.put("check_name", "NO_CHECK");
				parameterMap.put("check_name", "FORCE_CHECK");
				parameterMap.put("re_user_name", user.getUserName());
				parameterMap.put("desc", desc);
				parameterMap.put("spbill_create_ip","60.205.84.1");
				
				String sign = PayCommonUtil.createSign("UTF-8", parameterMap);
				parameterMap.put("sign", sign);
				
				String requestXML = PayCommonUtil.getRequestXml(parameterMap);
				logger.info("微信企业支付请求报文：" + requestXML);
				String result = PayCommonUtil.httpsRequestEnterprise(PayCommonUtil.ENTERPRISE_PAY_URL, requestXML);
				logger.info("企业支付返回报文："+result);
				Map<String,String> map = PayCommonUtil.doXMLParse(result);
				String return_code = map.get("return_code");
				String result_code = map.get("result_code");
				String partner_trade_no = map.get("partner_trade_no");
				String payment_no = map.get("payment_no");
				String payment_time = map.get("payment_time");
				
				if (return_code.equalsIgnoreCase(PayCommonUtil.SUCCESS)) {
					if (result_code.equalsIgnoreCase(PayCommonUtil.SUCCESS)) { 
						//修改提现表状态
						Withdraw withdraw = new Withdraw();
						withdraw.setUuid(partner_trade_no);
						withdraw.setWxid(payment_no);
						withdraw.setSucDate(DateUtils.parseDate(payment_time));
						withdraw.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
						withdrawService.updateWithdraw(withdraw);
						res.setCode(PayCommonUtil.SUCCESS_CODE);
						res.setDes("提现成功");
						logger.warn("修改体现表状态");
						//绑定用户微信
						try {
							if(flag){//不是首次更新微信信息
								UserWx userWxByUserId = userWxService.getUserWxByUserId(phone);
								userWxByUserId.setCity(userInfo.getCity());
								userWxByUserId.setCountry(userInfo.getCountry());
								userWxByUserId.setHeadimgurl(userInfo.getHeadImgUrl());
								userWxByUserId.setNickname(userInfo.getNickname());
								userWxByUserId.setProvince(userInfo.getProvince());
								userWxByUserId.setSex(userInfo.getSex());
//							userWxByUserId.setUpdateTime(new Date());
								userWxService.updateUserWx(userWxByUserId);
								logger.warn("修改微信信息");
							}else{//是首次绑定微信
								UserWx userWx = new UserWx();
								userWx.setUserId(phone);
								userWx.setCity(userInfo.getCity());
								userWx.setCountry(userInfo.getCountry());
								userWx.setCreateTime(new Date());
								userWx.setHeadimgurl(userInfo.getHeadImgUrl());
								userWx.setNickname(userInfo.getNickname());
								userWx.setOpenId(userInfo.getOpenId());
								userWx.setProvince(userInfo.getProvince());
								userWx.setSex(userInfo.getSex());
								userWx.setUnionid(userInfo.getUnionId());
								userWxService.addUserWx(userWx);
								logger.warn("增加微信信息");
							}
						} catch (Exception e) {
							e.printStackTrace();
							logger.error("提现成功保存微信信息错误："+JsonUtil.toJson(userInfo));
							return res;
						}
						return res;
					}else{
						String err_code = map.get("err_code");
						String err_code_des = map.get("err_code_des");
						Withdraw withdraw = new Withdraw();
						withdraw.setUuid(sn);
						withdraw.setErrorCode(err_code);
						withdraw.setReason(err_code_des);
						withdrawService.updateWithdraw(withdraw);  //保存微信返回错误信息
						logger.warn("保存微信返回错误信息："+JsonUtil.toJson(withdraw));
						refund(balance, sn, phone);
						logger.warn("调用微信企业支付：err_code"+err_code+",err_code_des"+err_code_des);
						if(err_code.equalsIgnoreCase("NAME_MISMATCH")){
							res.setCode(PayCommonUtil.WARN_CODE);
							res.setDes("姓名请与微信实名保持一致");
							return res;
						}
						res.setCode(PayCommonUtil.FAIL_CODE);
						res.setDes("提现失败，请联系管理员");
						return res;
					}
				}else {
					Withdraw withdraw = new Withdraw();
					withdraw.setUuid(partner_trade_no);
					withdraw.setStatus(PayCommonUtil.PENDING_QUERY_CODE);
					withdraw.setReason("网络错误，待查询");
					withdrawService.updateWithdraw(withdraw);  //记录网络错误后的待查询状态
					//TODO  可能网络出现错误，查询支付结果    线程池中查询支付结果
					this.taskExecutor.execute(new EnterpriseQueryTask(partner_trade_no));  
					res.setCode(PayCommonUtil.FAIL_CODE);
					res.setDes("系统繁忙");
					logger.error("调用微信企业付款通信异常");
					return res;
				}
			}else{
				res.setCode(PayCommonUtil.SUCCESS_CODE);
				res.setDes("您的提现申请已提交，预计2个工作日内到账");
				return res;
			}
		} catch (Exception e) {
			refund(balance, sn, phone);
			logger.warn("调用微信企业支付：,err_code_des"+e);
			res.setCode(PayCommonUtil.FAIL_CODE);
			res.setDes("提现失败，请联系管理员");
			return res;
		}
	}
}
